import React, { useState, useEffect, useCallback } from 'react';
import { message, Form, Input } from 'antd';
import ProForm, {
  ProFormText,
  ProFormTextArea,
  ProFormRadio,
  ProFormDigit,
} from '@ant-design/pro-form';
import { history } from 'umi';
import { SettingOutlined } from '@ant-design/icons';
import { saveMenu, getItemById, update } from '@/services/sysSetting';

const MenuOperation = (props: any) => {
  let {
    location: {
      state: { changeSubsystemCode, Id, jumpType },
    },
  } = props;
  // 资源编码是否可见
  const [subSystemCodeHidden, setSubSystemCodeHidden] = useState(true);
  // 控件ID是否可见
  const [permsHidden, setPermsHidden] = useState(false);
  // 详情页面不可编辑
  const [detailsNotEditable, setDetailsNotEditable] = useState(false);
  // 父级别ID
  const [parentId, setParentId] = useState('');
  const changeIconFun = () => {
    console.log('changeIconFun :>> ');
  };
  // 资源类型的选择为子系统时，资源编码显示
  const onValuesChange = (changedValues: any, allValues: any) => {
    if (Object.prototype.hasOwnProperty.call(changedValues, 'type')) {
      setSubSystemCodeHidden(changedValues.type === '1' ? true : false);
      setPermsHidden(changedValues.type === '3' ? true : false);
    }
  };
  return (
    <>
      <ProForm<{
        name: string;
        company?: string;
        useMode?: string;
      }>
        style={{ background: '#fff', padding: '24px' }}
        onValuesChange={onValuesChange}
        onFinish={async (values: any) => {
          let interfaceName = saveMenu;
          if (jumpType === 'edit') {
            values.id = Id;
            interfaceName = update;
          }
          // 列表项的编辑。而不是表头的编辑
          if (jumpType === 'add' && Id) {
            values.parentResourceId = parentId;
          }
          if (jumpType !== 'addSystem') {
            values.subsystemCode = changeSubsystemCode;
          } else {
            if (values.type !== '1') {
              values.subsystemCode = changeSubsystemCode;
            }
          }
          interfaceName(values).then((res) => {
            if (res.code === 200) {
              history.push({
                pathname: '/features/sysSetting/menu',
                state: 'callback',
              });
            } else {
              message.warn(res.message);
            }
          });
          // message.success('提交成功');
        }}
        params={{}}
        request={async () => {
          let defaultValues: any = { name: '' };
          if (jumpType === 'details') {
            setDetailsNotEditable(true);
          }
          if (Id) {
            await getItemById(Id).then((res) => {
              if (res.code === 200) {
                let resData = res.data;console.log('resData :>> ', resData);
                if (jumpType === 'edit' || jumpType === 'details') {
                  defaultValues = {
                    parentName: resData.parentName, // 父级资源名称
                    type: resData.type + '', // 资源类型
                    subsystemCode: resData.subsystemCode, // 资源编码
                    name: resData.name, //资源名称
                    perms: resData.perms, //控件ID
                    status: resData.status + '', // 资源状态
                    routeUrl: resData.routeUrl, // 访问地址
                    clientType: resData.clientType + '', // 终端类型
                    apiUrls: resData.apiUrls, // 权限标识
                    weightLevel: resData.weightLevel + '', // 资源权重
                    sortOrder: resData.sortOrder + '', // 资源排序
                    comments: resData.comments, // 备注
                  };
                } else {
                  defaultValues = {
                    parentName: resData.name, // 父级资源名称
                    clientType: resData.clientType + '', // 终端类型
                  };
                  setParentId(resData.id); // 父级资源id
                }

                setSubSystemCodeHidden(
                  defaultValues.type === '1' ? true : false,
                );
                
                setPermsHidden(defaultValues.type === '3' ? true : false);
              }
            });
          }
          // 这里配置默认值
          return defaultValues;
        }}
        submitter={{
          // 配置按钮文本
          searchConfig: {
            resetText: jumpType === 'details' ? '返回' : '取消',
            submitText: '提交',
          },
          // 配置按钮的属性
          submitButtonProps: {
            style: {
              // 隐藏提交按钮
              display: jumpType === 'details' ? 'none' : 'block',
            },
          },
          onReset: () => {
            history.push({
              pathname: '/features/sysSetting/menu',
            });
          },
        }}
      >
        <ProForm.Group>
          <p style={{ fontSize: '18px' }}>
            {jumpType === 'details'
              ? '查看'
              : jumpType === 'add'
              ? '新增'
              : '编辑'}
            资源
          </p>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            width="md"
            name="parentName"
            label="父级资源名称"
            disabled={true}
            rules={[{ required: false, message: '父级资源名称' }]}
            placeholder="父级资源名称"
          />
          <ProFormRadio.Group
            label="资源类型"
            name="type"
            disabled={detailsNotEditable}
            initialValue={jumpType === 'addSystem' ? '1' : '2'}
            rules={[{ required: true, message: '请选择资源类型' }]}
            options={[
              {
                value: '1',
                label: '子系统',
                disabled: jumpType !== 'addSystem',
              },
              {
                value: '2',
                label: '菜单',
                disabled: jumpType === 'addSystem',
              },
              {
                value: '3',
                label: '操作',
                disabled: jumpType === 'addSystem',
              },
            ]}
          />
        </ProForm.Group>
        <ProFormText
          hidden={!subSystemCodeHidden}
          width="md"
          name="subsystemCode"
          disabled={detailsNotEditable}
          label="资源编码"
          rules={[{ required: subSystemCodeHidden, message: '请输入资源编码' }]}
          placeholder="请输入资源编码"
        />
        <ProForm.Group>
          <ProFormText
            width="md"
            name="name"
            disabled={detailsNotEditable}
            label="资源名称"
            rules={[{ required: true, message: '请输入资源名称' }]}
            placeholder="请输入名称"
          />
          <ProFormRadio.Group
            label="资源状态"
            name="status"
            disabled={detailsNotEditable}
            initialValue="1"
            rules={[{ required: true, message: '请选择资源状态' }]}
            options={[
              {
                value: '1',
                label: '启用',
              },
              {
                value: '0',
                label: '停用',
              },
            ]}
          />
        </ProForm.Group>
        <ProFormText
          hidden={!permsHidden}
          width="md"
          name="perms"
          disabled={detailsNotEditable}
          label="控件ID"
          rules={[{ required: permsHidden, message: '请输入控件ID' }]}
          placeholder="请输入控件ID"
        />
        <ProForm.Group>
          <ProFormText
            name="routeUrl"
            disabled={detailsNotEditable}
            width="md"
            label="访问地址"
            rules={[{ required: true, message: '请输入访问地址' }]}
            placeholder="请输入访问地址"
          />
          <ProFormRadio.Group
            label="终端类型"
            name="clientType"
            disabled={detailsNotEditable}
            initialValue="1"
            rules={[{ required: true, message: '请选择终端类型' }]}
            options={[
              {
                value: '1',
                label: 'PC',
              },
              {
                value: '2',
                label: 'H5',
              },
              {
                value: '3',
                label: 'PAD',
              },
            ]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            name="apiUrls"
            disabled={detailsNotEditable}
            width="md"
            label="权限标识"
            rules={[{ required: true, message: '请输入API资源路径' }]}
            placeholder="请输入API资源路径，如：路径1；路径2"
          />

          <ProFormRadio.Group
            label="资源权重"
            name="weightLevel"
            disabled={detailsNotEditable}
            initialValue="-1"
            rules={[{ required: true, message: '请选择资源权重' }]}
            options={[
              {
                value: '-1',
                label: 'system',
              },
              {
                value: '1',
                label: 'admin',
              },
              {
                value: '2',
                label: '其他',
              },
            ]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            name="sortOrder"
            disabled={detailsNotEditable}
            width="md"
            label="资源排序"
            rules={[
              {
                required: true,
                pattern: /^[1-9]\d*$/,
                message: '请输入资源排序（正整数）',
              },
            ]}
            placeholder="请输入资源排序（正整数）"
          />

          <Form.Item name="icon" label="图标" valuePropName="value">
            <Input
              addonBefore={<SettingOutlined />}
              disabled={detailsNotEditable}
              value=""
              onClick={changeIconFun}
            />
          </Form.Item>
        </ProForm.Group>
        <ProFormTextArea
          width="xl"
          disabled={detailsNotEditable}
          label="备注"
          name="comments"
          placeholder="请输入备注"
        />
      </ProForm>
    </>
  );
};

export default MenuOperation;
